package com.lagou.utils;

import com.lagou.bean.Jdbc;
import org.apache.commons.dbcp.BasicDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/*
 * @className DBCPUtil
 * @description dbcp连接池
 * @author admin
 * @date 2022/7/8 23:09
 * */
public class DBCPUtil {

    // 2.创建连接池对象
    public static BasicDataSource bds = new BasicDataSource();

    // 4.从连接池获取连接
    public static Connection getConnection(Jdbc jdbc) throws SQLException {
        bds.setUrl(jdbc.getUrl());
        bds.setUsername(jdbc.getUser());
        bds.setDriverClassName(jdbc.getDriverName());
        bds.setPassword(jdbc.getPassword());
        Connection connection = bds.getConnection();
        return connection;
    }

    // 5.释放资源方法
    public static void close(Connection connection) {
        if (null != connection) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static void close(Connection connection, Statement statement) {
        if (null != statement) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (null != connection) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    // 5.关闭资源方法
    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (null != statement) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (null != connection) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
